﻿
#include "printview.h"
#include <QDebug>
#include <QTextDocument>
#include <QPageSetupDialog>
#include <QPrintDialog>
#include <QDateTime>
#include "cmaskprintview.h"
#ifdef QT_CONCURRENT_LIB
#include <QtConcurrent>
#endif // QT_CONCURRENT_LIB

QList<QImage> PrintView::m_imageList= {};

PrintView::PrintView(const QString &) : QPrintPreviewDialog()
{
    connect(this, &QPrintPreviewDialog::paintRequested, this, &PrintView::paintRequestedHandler);
}

void PrintView::SetPdfPath(const QString &path)
{
#ifndef Q_OS_WIN
    QFuture<void> future = QtConcurrent::run([&](){
        QPdfium pdfiumObj;
        pdfiumObj.loadFile(path);

        if(!pdfiumObj.isValid())
        {
            qDebug() << "pdf file is no vaild.";
            return;
        }

        int count = pdfiumObj.pageCount() ;
        if(0 == count)
        {
            qDebug() << "pdf file is page count is 0.";
            return;
        }

        m_imageList.clear();
        for(int i = 0; i < count; ++i )
        {
            QPdfiumPage page = pdfiumObj.page(i);
            QImage image  = page.image();
            m_imageList.append(image);
        }
    });
#endif
}

void PrintView::paintRequestedHandler(QPrinter *pPrinter)
{
#ifndef Q_OS_WIN
    QPainter painterPixmap;
    painterPixmap.begin(pPrinter);
    for(int j= 0 ; j < m_imageList.count(); j++)
    {
        QImage image = m_imageList[j];

        image = image.scaled( pPrinter->width(), pPrinter->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation );
        painterPixmap.setWindow(0, 0, image.width(), image.height());
        painterPixmap.drawImage(QRectF(0,0,image.width(), image.height()), image);
        if(j != (m_imageList.count() - 1))
        {
            pPrinter->newPage();
            pPrinter->setFullPage(true);
        }
    }
    painterPixmap.end();
#endif
}
